package com.yatong.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: YaTong
 * @description: 首页
 * @author: Mr.Guo
 * @create: 2018-09-25 15:42
 **/
@Controller
public class IndexController {


    @RequestMapping("/login")
    public String admin(Model model){
        return "login";
    }


    @RequestMapping("/index")
    public String index(Model model){

        model.addAttribute("username","雅彤");
        System.out.println("首页");
        return "index";
    }
    @PostMapping("/ajaxLogin")
    @ResponseBody
    public Map<String,Object> login(String username, String password, Model model){
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        // 执行认证登陆
//        subject.login(token);

        Map<String, Object> map = new HashMap<String, Object>();
        try {
            subject.login(token);
            map.put("token", subject.getSession().getId());
            map.put("msg", "登录成功");
        } catch (IncorrectCredentialsException e) {
            map.put("msg", "密码错误");
        } catch (LockedAccountException e) {
            map.put("msg", "登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            map.put("msg", "该用户不存在");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
    @RequestMapping("/logout")
    public String logout(){
        return "login";
    }



    @RequestMapping("/main")
    public String main(Model model){
//        System.out.println("欢迎页");
//        System.out.println("测试GIT欢迎页");
        return "main";
    }
}
